package com.bcqn.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcqn.common.CommonResponse;
import com.bcqn.enums.UserWorkStatus;
import com.bcqn.enums.YesyOrNo;
import com.bcqn.model.Advice;
import com.bcqn.model.Message;
import com.bcqn.model.User;
import com.bcqn.service.AdviceService;
import com.bcqn.service.MessageService;
import com.bcqn.service.UserService;
import com.bcqn.utils.AESUtil;
import com.bcqn.utils.WechatUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController extends CommonController {


    @Resource
    private UserService userService;

    @Resource
    private AdviceService adviceService;

    @Resource
    private MessageService messageService;

    private void addCookie(HttpServletResponse response, Cookie cookie, boolean isHttpOnly) {
        String name = cookie.getName();
        String value = cookie.getValue();
        int maxAge = cookie.getMaxAge();
        String path = cookie.getPath();
        String domain = cookie.getDomain();
        boolean isSecure = cookie.getSecure();
        StringBuilder buffer = new StringBuilder();
        buffer.append(name).append("=").append(value).append(";");

        if (maxAge == 0) {
            buffer.append("Expires=Thu Jan 01 08:00:00 CST 1970;");
        } else if (maxAge > 0) {
            buffer.append("Max-Age=").append(maxAge).append(";");
        }
        if (domain != null) {
            buffer.append("domain=").append(domain).append(";");
        }
        if (path != null) {
            buffer.append("path=").append(path).append(";");
        }
        if (isSecure) {
            buffer.append("secure;");
        }
        if (isHttpOnly) {
            buffer.append("HTTPOnly;");
        }
        response.addHeader("Set-Cookie", buffer.toString());
    }

    @PostMapping("/login")
    public CommonResponse login(@RequestParam(value = "code", required = false) String code,
                                @RequestParam(value = "canIUse", required = false) Integer canIUse, HttpServletResponse response) {
        JSONObject sessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
        String openid = sessionKeyOpenId.getString("openid");
        Cookie logCookie = new Cookie("_login_token", AESUtil.encode(openid));
        logCookie.setMaxAge(Integer.MAX_VALUE);
        logCookie.setPath("/");
        addCookie(response, logCookie, true);

        User dbUser = userService.getUserByOpenid(openid);
        if (dbUser == null && canIUse.equals(YesyOrNo.NO.value())) {
            User user = new User();
            user.setWxOpenid(openid);
            user.setCreateTime(new Date());
            if (userService.insertUser(user) == 1) {
                return CommonResponse.success(user);
            }
            return CommonResponse.fail("登录异常");
        }
        return CommonResponse.success(dbUser);
    }

    @PostMapping("/userInfo")
    public CommonResponse wxinfo(@RequestParam(value = "openid", required = false) String openid,
                                 @RequestParam(value = "rawData", required = false) String rawData,
                                 @RequestParam(value = "company", required = false) String company,
                                 @RequestParam(value = "school", required = false) String school,
                                 @RequestParam(value = "job", required = false) String job,
                                 @RequestParam(value = "realName", required = false) String realName,
                                 @RequestParam(value = "isInSchool", required = false) Integer isInSchool

    ) {

        log.info("openid--->" + openid);
        JSONObject rawDataJson = JSON.parseObject(rawData);
        User user = userService.getUserByOpenid(openid);
        if (user == null) {
            return CommonResponse.fail("用户不存在");
        }
        String nickName = rawDataJson.getString("nickName");
        String avatarUrl = rawDataJson.getString("avatarUrl");
        String gender = rawDataJson.getString("gender");
        String city = rawDataJson.getString("city");
        String country = rawDataJson.getString("country");
        String province = rawDataJson.getString("province");
        user.setRealName(realName);
        user.setSchool(school);
        user.setCompany(company);
        user.setUserName(nickName);
        user.setAvatar(avatarUrl);
        user.setSex(gender);
        user.setArea(country + "," + province + "," + city);

        if (UserWorkStatus.WORK.value().equals(isInSchool)) {
            user.setStatus(isInSchool);
            user.setPosition(job);
        }
        if (UserWorkStatus.SCHOOL.value().equals(isInSchool)) {
            user.setStatus(isInSchool);
            user.setPurposePosition(job);
        }

        int i = userService.updateUser(user);
        if (i > 0) {
            return CommonResponse.success();
        } else {
            return CommonResponse.fail("error");
        }
    }

    @PostMapping("/feedback")
    public CommonResponse insertAdvice(@RequestBody Advice advice,HttpServletRequest request) {
        advice.setOpenid(getOpenId(request));
        int i = adviceService.insertAdvice(advice);
        if (i > 0) {
            return CommonResponse.success("意见反馈成功");
        } else {
            return CommonResponse.fail("意见反馈失败");
        }
    }

    @GetMapping("/aboutMe")
    public CommonResponse aboutMe(@RequestParam(value = "maxId", required = false, defaultValue = "-1") Long maxId, HttpServletRequest request) {
        User user = userService.getUserByOpenid(getOpenId(request));
        return CommonResponse.success(messageService.getAboutMe(user.getUserId(), maxId));
    }

    @GetMapping("/getMeCount")
    public CommonResponse getMeCount(HttpServletRequest request) {
        User user = userService.getUserByOpenid(getOpenId(request));
        return CommonResponse.success(messageService.getMeCount(user.getUserId()));
    }

    @PostMapping("/read")
    public CommonResponse read(@RequestParam("id") Long id, HttpServletRequest request) {
        User user = userService.getUserByOpenid(getOpenId(request));
        Message message = messageService.getById(id);
        if (!message.getTriggeredUserId().equals(user.getUserId())) {
            throw new RuntimeException("用户无权限");
        }
        message.setHaveRead(String.valueOf(YesyOrNo.YES.value()));
        messageService.update(message);
        return CommonResponse.success();
    }

    @PostMapping("/readAll")
    public CommonResponse read(HttpServletRequest request) {
        User user = userService.getUserByOpenid(getOpenId(request));
        messageService.updateReadAll(user.getUserId());
        return CommonResponse.success();
    }
}